package com.itboye.mengwu.app.ui.aizhiwu;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.WindowManager;
import android.view.animation.AnimationUtils;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.itboye.config.GlobalConfig;
import com.itboye.core.alert.ByAlert;
import com.itboye.core.object.BaseActivity;
import com.itboye.core.object.ResultEntity;
import com.itboye.core.object.SpPublicParams;
import com.itboye.core.utils.ImageCompressAndUpload;
import com.itboye.core.utils.ImageCompressAndUpload.OnUploadlistener;
import com.itboye.core.utils.SPUtils;
import com.itboye.core.utils.TimesUtils;
import com.itboye.core.utils.XImageLoader;
import com.itboye.mengwu.R;
import com.itboye.mengwu.data.model.LuntanTieZiBean;
import com.itboye.mengwu.data.model.TieZiBaoHanReply.GetAList;
import com.itboye.mengwu.data.model.VIPPersonalBean;
import com.itboye.mengwu.data.presenter.ConfigAppPresenter;
import com.itboye.mengwu.data.presenter.TieZiPresenter;
import com.itboye.mengwu.luntan.comment.view.MyListView;
import com.itboye.mengwu.main.MainActivity;
import com.itboye.mengwu.widget.PhotoSelectFragment;
import com.itboye.mengwu.widget.PhotoSelectFragment.PhotoSelectListener;
import com.itboye.mengwu.widget.XScrollView;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Observable;
import java.util.Observer;

public class MengShiGuangLook extends BaseActivity implements Observer {

    public final int EXTERNAL_CAMERA_REQ_CODE = 11;
    public final int EXTERNAL_STORE_REQ_CODE = 12;
    PopupWindows popupWindows;
    //
    View headerView, footView;
    LinearLayout addLinte;
    MyListView listView;
    private MyAdapter adapter;
    TieZiPresenter presenter;
    private String tid;
    private String uid;
    private GetAList aList;
    RelativeLayout bottom;
    ArrayList<String> arrayListImg = new ArrayList<>();
    Button ok;
    ImageView add, back;
    private String path;
    EditText editContent;
    protected StringBuffer attachments = new StringBuffer();
    private ArrayList<String> uploadedUrl = new ArrayList<String>();
    TextView txtContent;
    String type;
    protected int imgPosition;
    ArrayList<String> updateArrayImage = new ArrayList<>();
    ImageView more;
    ImageView image;
    protected View popup;
    TextView weekday;
    TextView afternoon;
    TextView daxiao;
    TextView change_bg;
    String t_month;
    String t_year;
    String t_day;
    String t_week;
    String t_noon;
    String birtday;
    int tag = 0;
    XScrollView xScrollView;
    ConfigAppPresenter appPresenter;
    VIPPersonalBean vipPersonalBean;
    protected PopupWindow popupWindow;
    protected StringBuffer buffer;
    private TextView riqi;//当前时间/***liu***/
    LuntanTieZiBean bean = new LuntanTieZiBean();

    @Override
    public int initView() {
        // TODO Auto-generated method stub
        return R.layout.activity_mengshiguanglook;
    }
    // 当界面显示出来的时候回调
    @Override
    public void onWindowFocusChanged(boolean hasFocus) {
        super.onWindowFocusChanged(hasFocus);
        if (hasFocus) {
//            listView.setViewBounds();
        }
    }
    @SuppressLint("NewApi")
    @Override
    public void onMyCreate() {
        showProgressDialog("加载中，请稍后", true);
        uid = SPUtils.get(this, null, SpPublicParams.UID, "") + "";
        tid = getIntent().getStringExtra("tid");
        appPresenter = new ConfigAppPresenter(this);
        appPresenter.getGuanZhu(uid, uid);
        try {
            type = getIntent().getStringExtra("edit");
        } catch (Exception e) {
            // TODO: handle exception
        }
        if (VERSION.SDK_INT >= VERSION_CODES.KITKAT) {
            // 透明状态栏
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            // 透明导航栏
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }
        headerView = View.inflate(this,R.layout.item_mengshiguanglook_headview, null);
        riqi= (TextView) headerView.findViewById(R.id.riqi);
        riqi.setText(TimesUtils.onTimeShiGUnag()+"");
        xScrollView= (XScrollView) findViewById(R.id.xScrollView);
        xScrollView.scrollBy(0,0);
        image = (ImageView) headerView.findViewById(R.id.image);
        back= (ImageView) headerView.findViewById(R.id.back);
        more= (ImageView) headerView.findViewById(R.id.more);
        daxiao = (TextView) headerView.findViewById(R.id.daxiao);
        change_bg = (TextView) headerView.findViewById(R.id.change_bg);
        weekday = (TextView) headerView.findViewById(R.id.weekday);
        afternoon = (TextView) headerView.findViewById(R.id.afternoon);
        riqi = (TextView) headerView.findViewById(R.id.riqi);
        listView.addHeaderView(headerView);
        footView = LayoutInflater.from(this).inflate(
                R.layout.item_mengshiguang_footview2, null);
        txtContent = (TextView) footView.findViewById(R.id.txtContent);
        listView.addFooterView(footView);
//        listView.setParallaxImageView(image);
        adapter = new MyAdapter(arrayListImg);
        listView.setAdapter(adapter);
        presenter = new TieZiPresenter(this);
        if (!tid.equals("-1")) {// 查看详情
            presenter.zhutiXiangqing(uid, tid, "0");
            bottom.setVisibility(View.GONE);
        } else {// 发布
            bottom.setVisibility(View.VISIBLE);
        }
        if (type != null) {
            bottom.setVisibility(View.VISIBLE);
        }

        change_bg.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                tag = 1;
                new PopupWindows(MengShiGuangLook.this, v);

            }
        });
        ok.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                Log.e("!!!!type", type + "");
                if (TextUtils.isEmpty(editContent.getText())) {
                    ByAlert.alert("请输入文字解释！");
                    return;
                }
                if (attachments == null || adapter.arrayListImg.size() == 0) {
                    ByAlert.alert("请上传图片！");
                    return;
                }
                if (type == null) {

                    for (int i = 0; i < arrayListImg.size(); i++) {
                        attachments.append(arrayListImg.get(i) + ",");
                        ImageCompressAndUpload.getInstance().execute(
                                arrayListImg.get(i), new OnUploadlistener() {
                                    @Override
                                    public void OnSuccess(String resultData) {

                                        Log.e("!!!!11", type + "");

                                        Log.e("resultData", resultData + "");
                                        if (uploadedUrl.size() < arrayListImg
                                                .size()) {

                                            uploadedUrl.add(resultData);
                                        }
                                        if (uploadedUrl.size() == arrayListImg
                                                .size()) {
                                            Log.e("!!!!22", type + "");
                                            if (uploadedUrl.size() > 0) {
                                                Log.e("!!!!33", type + "");
                                                attachments = new StringBuffer();
                                                attachments.append(uploadedUrl
                                                        .get(0));
                                                for (int i = 1; i < uploadedUrl
                                                        .size(); i++) {
                                                    Log.e("~uploadedUrl",
                                                            uploadedUrl.get(i));
                                                    attachments.append(",")
                                                            .append(uploadedUrl
                                                                    .get(i));
                                                }
                                                // uploadedUrl.clear();
                                            }
                                            bean = new LuntanTieZiBean();
                                            bean.setUid(uid);
                                            // bean.setSubject(title);
                                            bean.setMessage(editContent
                                                    .getText().toString());
                                            bean.setAuthor((String) SPUtils
                                                    .get(MengShiGuangLook.this,
                                                            null,
                                                            SpPublicParams.NICK_NAME,
                                                            ""));
                                            bean.setFid(9 + "");
                                            bean.setAttachments(attachments);

                                            Log.e("attachmentsSSS", attachments
                                                    + "");

                                        }
                                        Log.e("uploadedUrl.size()",
                                                uploadedUrl.size() + "");
                                        Log.e("arrayListImg.size()",
                                                arrayListImg.size() + "");
                                        if (uploadedUrl.size() == arrayListImg
                                                .size()) {

                                            Log.e("attachmentsSSS!!!!",
                                                    attachments + "");
                                            bean.setMessage(editContent
                                                    .getText().toString());
                                            presenter.add(bean);

                                        }

                                    }

                                    @Override
                                    public void OnError(String resultData) {
                                        ByAlert.alert("发表出错了╰(￣▽￣)╭1");
                                        // toast.show();
                                    }
                                }, "bbs");

                    }

                    if (arrayListImg.size() == 0) {
                        LuntanTieZiBean bean = new LuntanTieZiBean();
                        bean.setUid(uid);
                        // bean.setSubject(title);
                        bean.setMessage(editContent.getText().toString());
                        bean.setAuthor((String) SPUtils.get(
                                MengShiGuangLook.this, null,
                                SpPublicParams.NICK_NAME, ""));
                        bean.setFid(9 + "");
                        bean.setAttachments(attachments);

                        presenter.add(bean);
                    }
                } else if ("edit".equals(type)) {
                    // ByAlert.alert("13456");
                    buffer = new StringBuffer();
                    Log.e("arrayListImg.size()", arrayListImg.size() + "");
                    for (int i = 0; i < arrayListImg.size()
                            - updateArrayImage.size(); i++) {
                        System.out.println("图片原来的" + arrayListImg.get(i));
                        if (i < arrayListImg.size()) {
                            buffer.append(arrayListImg.get(i) + ",");
                            Log.e("!!!~~!", buffer.toString());
                        }
                    }

                    Log.e("updateArrayImage.size()", updateArrayImage.size()
                            + "");
                    for (int i = 0; i < updateArrayImage.size(); i++) {
                        attachments.append(updateArrayImage.get(i) + ",");
                        ImageCompressAndUpload.getInstance().execute(
                                updateArrayImage.get(i),
                                new OnUploadlistener() {
                                    @Override
                                    public void OnSuccess(String resultData) {
                                        uploadedUrl.add(resultData);
                                        Log.e("uploadedUrl.size()",
                                                uploadedUrl.size() + "");

                                        if (uploadedUrl.size() == updateArrayImage
                                                .size()) {
                                            if (uploadedUrl.size() > 0) {

                                                attachments = new StringBuffer();
                                                attachments.append(uploadedUrl
                                                        .get(0));
                                                for (int i = 1; i < uploadedUrl
                                                        .size(); i++) {
                                                    attachments.append(",")
                                                            .append(uploadedUrl
                                                                    .get(i));

                                                }

                                            }

                                            // if (uploadedUrl.size() ==
                                            // updateArrayImage.size()) {
                                            // System.out.println(tid+
                                            // "tid"+attachments.append(",").append(buffer).toString());

                                            Log.e("!!!!",
                                                    attachments.toString());
                                            Log.e("!!!!", buffer.toString());
                                            // Log.e("!!!!",
                                            // attachments.append(",").append(buffer).toString());
                                            // Log.e("!!!!",
                                            // buffer.append(attachments).toString());
                                            presenter.editMyTieZi(uid, tid,
                                                    editContent.getText()
                                                            .toString(),
                                                    buffer.append(attachments)
                                                            .toString());
                                            // }
                                        }

                                    }

                                    @Override
                                    public void OnError(String resultData) {
                                        ByAlert.alert("发表出错了╰(￣▽￣)╭2");
                                        // toast.show();
                                    }
                                }, "bbs");
                    }
                    if (updateArrayImage.size() == 0) {
                        System.out.println(tid
                                + "tid"
                                + attachments.append(",").append(buffer)
                                .toString());

                        Log.e("wwww", buffer + "");
                        buffer.toString().substring(0, buffer.length());
                        if (buffer.length() >= 1) {
                            presenter.editMyTieZi(uid, tid, editContent
                                            .getText().toString(),

                                    buffer.toString().substring(0, buffer.length() - 1));

                        } else {
                            ByAlert.alert("至少保留一张图片");
                            presenter.editMyTieZi(uid, tid, editContent
                                            .getText().toString(),

                                    "");

                        }

                    }
                }
            }
        });
        more.setVisibility(View.GONE);
        more.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                popup = LayoutInflater.from(MengShiGuangLook.this).inflate(
                        R.layout.popup_more, null);
                TextView collection = (TextView) popup
                        .findViewById(R.id.collection);
                TextView homepage = (TextView) popup
                        .findViewById(R.id.homepage);
                collection.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        // popupWindow.dismiss();
                    }
                });
                homepage.setOnClickListener(new OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        // TODO Auto-generated method stub
                        Intent intent = new Intent(MengShiGuangLook.this,
                                MainActivity.class);
                        startActivity(intent);
                        popupWindow.dismiss();
                        finish();
                    }
                });
                popupWindow = new PopupWindow(popup, 200,
                        LayoutParams.WRAP_CONTENT);
                popupWindow.setOutsideTouchable(true);
                popupWindow.setBackgroundDrawable(new BitmapDrawable());
                popupWindow.showAsDropDown(v);
            }
        });
        back.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                setResult(102);
                finish();
            }
        });
        add.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                tag = 0;
                popupWindows = new PopupWindows(MengShiGuangLook.this, v);
            }
        });
    }

    public class PopupWindows extends PopupWindow {

        public PopupWindows(Context mContext, View parent) {

            View view = View
                    .inflate(mContext, R.layout.item_popupwindows, null);
            view.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.fade_ins));
            LinearLayout ll_popup = (LinearLayout) view
                    .findViewById(R.id.ll_popup);
            ll_popup.startAnimation(AnimationUtils.loadAnimation(mContext,
                    R.anim.push_bottom_in_2));

            setWidth(LayoutParams.FILL_PARENT);
            setHeight(LayoutParams.FILL_PARENT);
            setBackgroundDrawable(new BitmapDrawable());
            setFocusable(true);
            setOutsideTouchable(true);
            setContentView(view);
            showAtLocation(parent, Gravity.BOTTOM, 0, 0);

            Button bt1 = (Button) view
                    .findViewById(R.id.item_popupwindows_camera);
            Button bt2 = (Button) view
                    .findViewById(R.id.item_popupwindows_Photo);
            Button bt3 = (Button) view
                    .findViewById(R.id.item_popupwindows_cancel);

            bt1.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {

                    cameraPermission();

                }
            });
            bt2.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    // Intent intent = new
                    // Intent(ActivityAiwujiaMomPublish.this,
                    // AiWuJiaTestPicActivity.class);
                    // intent.putExtra("hu", HU);
                    // startActivityForResult(intent, 1100);
                    // dismiss();
                    // finish();
                    // if (tag==1) {
                    // PhotoSelect photoSelect=new PhotoSelect();
                    // }else {
                    // new PhotoSelectFragment(new PhotoSelect(),
                    // 9).show(getSupportFragmentManager(), null);
                    // dismiss();
                    // }
                    storePermission();
                }
            });
            bt3.setOnClickListener(new OnClickListener() {
                public void onClick(View v) {
                    dismiss();
                }
            });
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // TODO Auto-generated method stub
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            setResult(102);
            finish();
        }
        return super.onKeyDown(keyCode, event);
    }

    private static final int TAKE_PICTURE = 0x000000;

    public void photo() {
        Intent openCameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        File file = new File(Environment.getExternalStorageDirectory()
                + "/myimage/", String.valueOf(System.currentTimeMillis())
                + ".jpg");
        path = file.getPath();
        Uri imageUri = Uri.fromFile(file);
        openCameraIntent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri);
        startActivityForResult(openCameraIntent, TAKE_PICTURE);
        //

    }

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case TAKE_PICTURE:
                if (arrayListImg.size() < 9 && requestCode == TAKE_PICTURE
                        && resultCode == RESULT_OK && tag != 1) {

                    if (type != null) {
                        updateArrayImage.add(path);
                    }
                    arrayListImg.add(path);
                    adapter.notifyDataSetChanged();
                }
                if (tag == 1) {
                    Log.e("!!!!!!", "切换背景！！！");
                    ImageCompressAndUpload.getInstance().execute(path,
                            new OnUploadlistener() {

                                @Override
                                public void OnSuccess(String resultData) {
                                    // uploadedUrl.add(resultData);
                                    XImageLoader.load(GlobalConfig.API_URL
                                                    + "/picture/index?id=" + resultData,
                                            image);
                                    System.out.println("rse" + resultData);

                                }

                                @Override
                                public void OnError(String resultData) {
                                    ByAlert.alert("发表出错了╰(￣▽￣)╭");
                                    // toast.show();
                                }
                            }, "bg");

                } else {
                    adapter.notifyDataSetChanged();
                }

                break;
        }
    }

    OnClickListener deleteClickListener = new OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            imgPosition = (int) v.getTag();
            // presenter.deleteImage(uid, tid, aList.getImg().get(imgPosition));

            arrayListImg.remove(imgPosition);
            // updateArrayImage.remove(imgPosition);
            adapter.notifyDataSetChanged();
        }
    };

    class PhotoSelect implements PhotoSelectListener {

        @Override
        public void onPhotoSelectFinish(List<String> paths) {
            for (String string : paths) {
                if (type != null & tag != 1) {
                    updateArrayImage.add(string);
                    arrayListImg.add(string);
                } else if (type == null & tag != 1) {
                    updateArrayImage.add(string);
                    arrayListImg.add(string);
                }

            }
            if (tag == 1) {
                ImageCompressAndUpload.getInstance().execute(paths.get(0),
                        new OnUploadlistener() {

                            @Override
                            public void OnSuccess(String resultData) {
                                // uploadedUrl.add(resultData);
                                Log.e("~~~", "uploadSuccess");
                                XImageLoader.load(GlobalConfig.API_URL
                                                + "/picture/index?id=" + resultData,
                                        image);
                                System.out.println("rseuploadSuccess" + resultData);

                            }

                            @Override
                            public void OnError(String resultData) {
                                Log.e("~~~", "uploadError");
                                ByAlert.alert("发表出错了╰(￣▽￣)╭");
                                // toast.show();
                            }
                        }, "bg");

            } else {
                adapter.notifyDataSetChanged();
            }

        }

    }

//    @Override
//    public void onWindowFocusChanged(boolean hasFocus) {
//        // TODO Auto-generated method stub
//        super.onWindowFocusChanged(hasFocus);
//        RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
//                RelativeLayout.LayoutParams.WRAP_CONTENT,
//                RelativeLayout.LayoutParams.WRAP_CONTENT);
//        params.setMargins(0, getStatusBarHeight(), 0, 0);
//        findViewById(R.id.top).setLayoutParams(params);
//    }

    public class MyAdapter extends BaseAdapter {
        ArrayList<String> arrayListImg;

        public MyAdapter(ArrayList<String> arrayListImg) {
            this.arrayListImg = arrayListImg;
        }

        public void delete(ArrayList<String> arrayListImg) {
            this.arrayListImg = arrayListImg;
        }

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            return arrayListImg == null ? 0 : arrayListImg.size();
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return arrayListImg == null ? 0 : arrayListImg.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = LayoutInflater.from(MengShiGuangLook.this)
                        .inflate(R.layout.item_mengshiguangdetail, null);
                holder = new ViewHolder();
                holder.textView = (TextView) convertView.findViewById(R.id.txt);
                holder.delete = (ImageView) convertView
                        .findViewById(R.id.delete);
                holder.datu = (ImageView) convertView.findViewById(R.id.image);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }
            if (type == null) {
                holder.delete.setVisibility(View.GONE);
            } else {
                holder.delete.setVisibility(View.VISIBLE);
                holder.delete.setTag(position);
                holder.delete.setOnClickListener(deleteClickListener);
            }
            if (arrayListImg != null) {
                if (arrayListImg.get(position).startsWith("/storage")) {
                    XImageLoader.load("file://" + arrayListImg.get(position),
                            holder.datu);
                } else {
                    XImageLoader.load(GlobalConfig.API_URL + "/picture/index?id="
                            + arrayListImg.get(position), holder.datu);
                }
            }
            // holder.datu.se
            return convertView;
        }

        public class ViewHolder {
            TextView textView;
            ImageView delete;
            ImageView datu;
        }

    }

    @SuppressWarnings("deprecation")
    @Override
    public void update(Observable observable, Object data) {
        // TODO Auto-generated method stub
        ResultEntity entity = handlerError(data);
        if (entity != null) {
            if (entity.getEventType() == TieZiPresenter.XiangQingSuccess) {
                aList = (GetAList) entity.getData();
                arrayListImg.clear();
                arrayListImg.addAll(aList.getImg());
                adapter.notifyDataSetChanged();
                // aList.get
                DateChange(aList.getDateline());

                if (aList.getBabyDefault().getBirthday() != null) {
                    babybirth(aList.getBabyDefault().getBirthday());
                    daxiao.setText(birtday);
                } else {
                    daxiao.setText("还没宝宝");
                }

                weekday.setText(t_week);
                afternoon.setText(t_noon);
                riqi.setText(t_year + "." + t_month + "." + t_day);
//                listView.addHeaderView(headerView);

                if (type != null) {
                    editContent.setText(aList.getMessage());
                    txtContent.setVisibility(View.GONE);
                } else {
                    txtContent.setText(aList.getMessage());
                    txtContent.setVisibility(View.VISIBLE);
                }
            } else if (entity.getEventType() == TieZiPresenter.XiangQingFail) {
                // ByAlert.alert("" + entity.getData());

            } else if (entity.getEventType() == ConfigAppPresenter.Guanzhu_success) {
                vipPersonalBean = (VIPPersonalBean) entity.getData();
                if (vipPersonalBean.getBg_img() != null
                        && vipPersonalBean.getBg_img() != "") {
                    if (vipPersonalBean.getBg_img() != null && !"".equals(vipPersonalBean.getBg_img())) {
                        XImageLoader.load(
                                GlobalConfig.API_URL + "/picture/index?id="
                                        + vipPersonalBean.getBg_img(), image);
                        image.setVisibility(View.VISIBLE);
                        Log.d("imageimageimageimage",vipPersonalBean.getBg_img()+"");
                    } else {

                    }

                } else {
                    image.setBackground(getResources().getDrawable(
                            R.drawable.gerenbac));
                }

            } else if (entity.getEventType() == TieZiPresenter.AddTieZiSuccess) {

                // ByAlert.alert(entity.getData() + "");
                setResult(102);
                finish();
            } else if (entity.getEventType() == TieZiPresenter.AddTieZiFail) {
                ByAlert.alert(entity.getData() + "");
            } else if (entity.getEventType() == TieZiPresenter.ImageDeleteSuccess) {
                // ByAlert.alert(entity.getData() + "");
                presenter.zhutiXiangqing(uid, tid, "0");
            } else if (entity.getEventType() == TieZiPresenter.ImageDeleteFail) {
                // ByAlert.alert(entity.getData() + "");
            } else if (entity.getEventType() == TieZiPresenter.MengTimesEditSuccess) {
                // ByAlert.alert(entity.getData() + "");
                setResult(102);
                finish();
            } else if (entity.getEventType() == TieZiPresenter.MengTimesEditFail) {
                // ByAlert.alert(entity.getData() + "");
            }
        }
        try {
            closeProgressDialog();
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    private void DateChange(String date) {
        Calendar calendar2 = Calendar.getInstance();
        long timews = Long.valueOf(date);
        Date dates = new Date(timews * 1000L);
        calendar2.setTime(dates);
        int year = calendar2.get(Calendar.YEAR);
        int month = calendar2.get(Calendar.MONTH);
        int day_year = calendar2.get(Calendar.DAY_OF_MONTH);
        t_day = day_year + "";
        int day = calendar2.get(Calendar.DAY_OF_WEEK);
        t_year = year + "";
        t_month = month + 1 + "";
        if (day == 1) {
            t_week = "星期日";
        } else if (day == 2) {
            t_week = "星期一";
        } else if (day == 3) {
            t_week = "星期二";
        } else if (day == 4) {
            t_week = "星期三";
        } else if (day == 5) {
            t_week = "星期四";
        } else if (day == 6) {
            t_week = "星期五";
        } else if (day == 7) {
            t_week = "星期六";
        }
        SimpleDateFormat myFmt2 = new SimpleDateFormat("HH");
        String afternoon = myFmt2.format(Long.parseLong(date) * 1000L);
        if (Integer.parseInt(afternoon) < 12) {
            t_noon = "上午";
        } else {
            t_noon = "下午";
        }
    }

    private void babybirth(String birth) {
        SimpleDateFormat myFmt1 = new SimpleDateFormat("yyyy年MM月dd日");
        Calendar calendar = Calendar.getInstance();
        int yearNow = calendar.get(Calendar.YEAR);
        int monthNow = calendar.get(Calendar.MONTH);
        int dayNow = calendar.get(Calendar.DAY_OF_MONTH);
        Log.d("hu-----", yearNow + "monthNow-----" + "-------dayBirth"
                + monthNow + "n" + dayNow);
        Calendar calendar2 = Calendar.getInstance();
        if (birth != null) {
            long timews = Long.valueOf(birth);
            Date date = new Date(timews * 1000L);
            calendar2.setTime(date);
            int yearBirth = calendar2.get(Calendar.YEAR);
            int monthBirth = calendar2.get(Calendar.MONTH);
            int dayBirth = calendar2.get(Calendar.DAY_OF_MONTH);
            Log.d("hu-----2", yearBirth + "monthBirth-----" + "-------dayBirth"
                    + monthBirth + "n" + dayBirth);
            int age = yearNow - yearBirth;
            int month = monthNow - monthBirth;
            int day = dayNow - dayBirth;
            if (age > 0) {
                if (month > 0) {
                    if (day < 0) {
                        month--;
                        age--;
                    }
                } else if (month < 0) {
                    month += 12;
                    if (day < 0) {
                        month--;
                        age--;
                    }
                }
            } else {
                if (day < 0) {
                    month--;
                }

            }
            SimpleDateFormat myFmt5 = new SimpleDateFormat("d");
            String birthday2 = myFmt1
                    .format(Long.parseLong((birth) + "") * 1000L);
            String birthday = myFmt5.format(System.currentTimeMillis()
                    - Long.parseLong((birth) + "") * 1000L);
            int days = Integer.parseInt(birthday) % 30 - 1;
            Log.d("hu-bir", birthday2);
            Log.d("hu-old", (age + "岁" + month + "月" + days + "天"));
            if (age == 0) {
                if (month == 0) {
                    birtday = (+days + "天");
                } else if (days == 0) {
                    birtday = (month + "月整");
                } else if (days != 0) {
                    birtday = (month + "月" + days + "天");
                }
            } else if (month == 0) {
                if (days == 0) {
                    birtday = (age + "岁整");
                } else {
                    birtday = (age + "岁" + days + "天");

                }
            } else if (month != 0) {
                if (days == 0) {
                    birthday = (age + "岁" + month + "月整");
                } else {
                    birthday = (age + "岁" + month + "月" + days + "天");
                }
            }

        }
    }

    public void cameraPermission() {
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA) != PackageManager.PERMISSION_GRANTED) {

            // 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.CAMERA)) {
                Toast.makeText(this, "请去设置给小萌添加个权限，否则打不开相机。",
                        Toast.LENGTH_SHORT).show();
            } else {
                // 进行权限请求
                ActivityCompat.requestPermissions(this, new String[]{
                                Manifest.permission.CAMERA,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE},
                        EXTERNAL_CAMERA_REQ_CODE);
            }
        } else {
            photo();
            // popupWindows.dismiss();
        }
    }

    public void storePermission() {
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {

            // 如果App的权限申请曾经被用户拒绝过，就需要在这里跟用户做出解释
            if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                    Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                Toast.makeText(this, "请去设置给小萌添加个权限，否则不能读取相册。",
                        Toast.LENGTH_SHORT).show();
            } else {
                // 进行权限请求
                ActivityCompat.requestPermissions(this, new String[]{
                                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                                Manifest.permission.READ_EXTERNAL_STORAGE},
                        EXTERNAL_STORE_REQ_CODE);
            }
        } else {
            new PhotoSelectFragment(new PhotoSelect(), 9).show(
                    getSupportFragmentManager(), null);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] arg1,
                                           int[] grantResults) {
        // TODO Auto-generated method stub
        super.onRequestPermissionsResult(requestCode, arg1, grantResults);

        switch (requestCode) {

            case EXTERNAL_CAMERA_REQ_CODE: {
                if (grantResults == null || "".equals(grantResults)) {
                    return;
                } else {
                    if (grantResults.length > 0
                            && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                        // 申请成功，进行相应操作
                        photo();
                        popupWindows.dismiss();
                    } else {
                        // 申请失败，可以继续向用户解释。

                    }
                }
                return;
            }
            case EXTERNAL_STORE_REQ_CODE: {

                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 申请成功，进行相应

                    PhotoSelectFragment photoSelectFragment = new PhotoSelectFragment(
                            new PhotoSelect(), 9);
                    photoSelectFragment.show(getSupportFragmentManager(), null);

                } else {
                    // 申请失败，可以继续向用户解释。

                }
                return;
            }
        }
    }

    @Override
    protected void onSaveInstanceState(Bundle arg0) {
        // TODO Auto-generated method stub
        // super.onSaveInstanceState(arg0);
    }
}
